//
//  RGMainPageListCell.m
//  RedGrass
//
//  Created by wukong on 2018/11/26.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "RGMainPageListCell.h"
#import "RGFocusView.h"
#import "RGFavoriteView.h"
#import "RGDescriptionView.h"
#import "RGVedioNameAnimationView.h"
#import <UIImageView+WebCache.h>
#import "RGBottomCommentToolBar.h"



@interface RGMainPageListCell()

//@property (nonatomic, strong) UIImageView      *bgView;
@property (nonatomic, strong) UIImageView      *avatar;
@property (nonatomic, strong) RGFocusView      *focus;
@property (nonatomic, strong) UIImageView      *share;
@property (nonatomic, strong) UIImageView      *comment;
@property (nonatomic, strong) RGFavoriteView   *favorite;
@property (nonatomic, strong) UILabel          *shareNum;
@property (nonatomic, strong) UILabel          *commentNum;
@property (nonatomic, strong) UILabel          *favoriteNum;
@property (nonatomic, strong) UIView                   *container;
@property (nonatomic ,strong) CAGradientLayer          *gradientLayer;
@property (nonatomic ,strong) UIImageView              *pauseIcon;
@property (nonatomic, strong) UITapGestureRecognizer   *singleTapGesture;
@property (nonatomic, assign) NSTimeInterval           lastTapTime;
@property (nonatomic, assign) CGPoint                  lastTapPoint;
@property (nonatomic, strong) UIImageView              *vedioBackImg;
@property (nonatomic, strong) UIView                   *playerView;
@property (nonatomic, strong) RGBottomCommentToolBar   *bottomCommentToolBar;


@property (nonatomic, strong) RGDescriptionView *descriptionView;
//@property (nonatomic, strong) RGVedioNameAnimationView *animationView;
@property (nonatomic, strong) UIImageView *musicImg;



@end

@implementation RGMainPageListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = UICOLOR_WITH_RGBINT_A(0x000000, 0.1);
        self.lastTapTime = 0;
        self.lastTapPoint = CGPointZero;
        [self initSubViews];
    }
    return self;
}


- (void)initSubViews {
    
    [self.contentView addSubview:self.container];
    
    [_container addGestureRecognizer:self.singleTapGesture];
    [_container.layer addSublayer:self.gradientLayer];
    [_container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [_container addSubview:self.vedioBackImg];
    [_vedioBackImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [_container addSubview:self.playerView];
    [_playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
  
    
    [_container addSubview:self.pauseIcon];
    [_pauseIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.contentView);
        make.width.height.mas_equalTo(100);
    }];
    
//    [_container addSubview:self.musicImg];
//    [_musicImg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(self.contentView).mas_offset(20);
//        make.bottom.equalTo(self.contentView).mas_offset(-100);
//
//    }];
//
//    [_container addSubview:self.animationView];
//    [_animationView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.mas_equalTo(self.musicImg.mas_centerY).mas_offset(0);
//        make.left.mas_equalTo(self.musicImg.mas_right).mas_offset(10);
//        make.right.mas_equalTo(self.contentView).mas_offset(-80);
//        make.height.mas_equalTo(25);
//    }];
    
    [_container addSubview:self.descriptionView];
    [_descriptionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.contentView).mas_offset(-80);
//        make.bottom.mas_equalTo(self.musicImg.mas_top).mas_offset(-8);
        make.left.mas_equalTo(self.contentView).mas_offset(0);
        make.right.mas_equalTo(self.contentView).mas_offset(-80);
        make.height.mas_equalTo(100);
    }];
    
    [_container addSubview:self.share];
    [_share mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.contentView).offset(-200);
        make.right.mas_equalTo(self.contentView).offset(-10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    
    [_container addSubview:self.shareNum];
    [_shareNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.share.mas_bottom);
        make.centerX.equalTo(self.share);
    }];

    [_container addSubview:self.comment];
    [_comment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.share.mas_top).inset(25);
        make.right.equalTo(self).inset(10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    
    [_container addSubview:self.commentNum];
    [_commentNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.comment.mas_bottom);
        make.centerX.equalTo(self.comment);
    }];
    
    [_container addSubview:self.favorite];
    [_favorite mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.comment.mas_top).inset(25);
        make.right.equalTo(self).inset(10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(45);
    }];
    
    [_container addSubview:self.favoriteNum];
    [_favoriteNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.favorite.mas_bottom);
        make.centerX.equalTo(self.favorite);
    }];
    
    [_container addSubview:self.avatar];
    [_avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.favorite.mas_top).inset(35);
        make.right.equalTo(self).inset(10);
        make.width.height.mas_equalTo(50);
    }];
    
    [_container addSubview:self.focus];
    [_focus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.avatar);
        make.centerY.equalTo(self.avatar.mas_bottom);
        make.width.height.mas_equalTo(24);
    }];
}


-(void)prepareForReuse {
    [super prepareForReuse];
    

    [_pauseIcon setHidden:NO];
    [_avatar setImage:[UIImage imageNamed:@"头像"]];
    [_favorite resetView];
    [_focus resetView];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    _gradientLayer.frame = CGRectMake(0, KScreenHeight - 500, KScreenWidth, 500);
    [CATransaction commit];
}

#pragma mark - public

-(void) setVideoModel:(RGRecommendVideoModel *)videoModel{
    if(!videoModel){
        return;
    }
    _videoModel = videoModel;

    [_vedioBackImg sd_setImageWithURL:[NSURL URLWithString:SafeStr(videoModel.coverPath)]];
    
    NSString *userIconUrl = videoModel.videoUser.image;
    [_avatar sd_setImageWithURL:[NSURL URLWithString:SafeStr(userIconUrl)] placeholderImage:IMAGE_NAMED(@"头像")];
    //喜欢
    [_favorite showOriginalUIStyleWhenFirstLoadWithIsFavorite:videoModel.isLike];
    _favoriteNum.text = [self makeCountStrWithNumber:videoModel.likeCounts];
    //评论数
    _commentNum.text = [self makeCountStrWithNumber:videoModel.commentsCounts];
    //分享
    _shareNum.text = [self makeCountStrWithNumber:videoModel.forwardCounts];
    //描述
    [_descriptionView updateUserName:videoModel.videoUser.nickname userDes:videoModel.videoDesc];
    //关注
    if([self videoUserIsSelfWithId:videoModel.videoUser.ID]){
        _focus.hidden = YES;
    }else{
        _focus.hidden = NO;
        BOOL isFocus = videoModel.videoUser.meFollowmTa;
        [_focus updateOriginalUiStyleWithIsfocus:isFocus];
    }
   
}

//判断是不是自己的视频
-(BOOL) videoUserIsSelfWithId:(NSInteger)userId{
    NSInteger myId = [RGUserInfoModel getUserInfo].ID;
    return userId == myId ? YES : NO;
}

-(void) setIsShowBottomToolBar:(BOOL)isShowBottomToolBar{
    _isShowBottomToolBar = isShowBottomToolBar;
    if(isShowBottomToolBar){
        [self.container addSubview:self.bottomCommentToolBar];
        [_bottomCommentToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.container).mas_offset(0);
            make.height.mas_equalTo(50);
            if(@available(iOS 11.0, *)){
                 make.bottom.mas_equalTo(self.container).mas_offset(-10 - 34);
            }else{
                make.bottom.mas_equalTo(self.container).mas_offset(-10);
            }
        }];
    }
}


-(void) begainFocusAnimationWithIsFocus:(BOOL)isFocus{
    [_focus begainAnimationWithIsFocus:isFocus];
}

-(void) begainFavoriteAnimationWithIsFavorite:(BOOL)isFavorite{
    [_favorite begainAnimationWithIsFavorite:isFavorite];
    _favoriteNum.text = [self makeCountStrWithNumber:_videoModel.likeCounts];
}

-(void) showFavoriteUIStyleWhenIsFavorite:(BOOL)favorite{
    [_favorite showOriginalUIStyleWhenFirstLoadWithIsFavorite:favorite];
    _favoriteNum.text = [self makeCountStrWithNumber:_videoModel.likeCounts];
}

//更新评论数
-(void) updateCommentCounts{
    _commentNum.text = [self makeCountStrWithNumber:_videoModel.commentsCounts];
}

//更新转发数
-(void) updateForwardCounts{
    _shareNum.text = [self makeCountStrWithNumber:_videoModel.forwardCounts];
}

#pragma mark - private

-(NSString *)makeCountStrWithNumber:(NSInteger)num{
    if(num < 10000){
        return [NSString stringWithFormat:@"%ld",num];
    }
    float tempNum = num / 10000;
    return [NSString stringWithFormat:@"%0.1fW",ceil(tempNum)];
}

//gesture
- (void)handleGesture:(UITapGestureRecognizer *)sender {
    
    switch (sender.view.tag) {
        case kAwemeListLikeCommentTag: {
            if(self.actionItemClickBlock){
                self.actionItemClickBlock(kAwemeListLikeCommentTag);
            }
           
        }
             break;
        case kAwemeListLikeShareTag: {
            if(self.actionItemClickBlock){
                self.actionItemClickBlock(kAwemeListLikeShareTag);
            }
           
        }
             break;
        case kAwemeListLikeUserIconTag:{//点击用户头像
            if(self.actionItemClickBlock){
                self.actionItemClickBlock(kAwemeListLikeUserIconTag);
            }
        }
            break;
        default: {
            //获取点击坐标，用于设置爱心显示位置
            CGPoint point = [sender locationInView:self.container];
            //获取当前时间
            NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
            //判断当前点击时间与上次点击时间的时间间隔
            if(time - self.lastTapTime > 0.25f) {
                //推迟0.25秒执行单击方法
                [self performSelector:@selector(singleTapAction) withObject:nil afterDelay:0.25f];
            }else {
                //取消执行单击方法
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTapAction) object: nil];
                //执行连击显示爱心的方法
                //暂时取消
//                [self showLikeViewAnim:point oldPoint:self.lastTapPoint];
            }
            //更新上一次点击位置
            self.lastTapPoint = point;
            //更新上一次点击时间
            self.lastTapTime =  time;
            break;
        }
    }
}

//暂停播放动画
- (void)showPauseViewAnim:(CGFloat)rate {
    if(rate == 0) {
        [UIView animateWithDuration:0.25f
                         animations:^{
                             self.pauseIcon.alpha = 0.0f;
                         } completion:^(BOOL finished) {
                             [self.pauseIcon setHidden:YES];
                         }];
    }else {
        [_pauseIcon setHidden:NO];
        _pauseIcon.transform = CGAffineTransformMakeScale(1.8f, 1.8f);
        _pauseIcon.alpha = 1.0f;
        [UIView animateWithDuration:0.25f delay:0
                            options:UIViewAnimationOptionCurveEaseIn animations:^{
                                self.pauseIcon.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                            } completion:^(BOOL finished) {
                            }];
    }
}

//连击爱心动画
- (void)showLikeViewAnim:(CGPoint)newPoint oldPoint:(CGPoint)oldPoint {
    UIImageView *likeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_home_like_after"]];
    CGFloat k = ((oldPoint.y - newPoint.y)/(oldPoint.x - newPoint.x));
    k = fabs(k) < 0.5 ? k : (k > 0 ? 0.5f : -0.5f);
    CGFloat angle = M_PI_4 * -k;
    likeImageView.frame = CGRectMake(newPoint.x, newPoint.y, 80, 80);
    likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 0.8f, 1.8f);
    [self.container addSubview:likeImageView];
    [UIView animateWithDuration:0.2f
                          delay:0.0f
         usingSpringWithDamping:0.5f
          initialSpringVelocity:1.0f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 1.0f, 1.0f);
                     }
                     completion:^(BOOL finished) {
                         [UIView animateWithDuration:0.5f
                                               delay:0.5f
                                             options:UIViewAnimationOptionCurveEaseOut
                                          animations:^{
                                              likeImageView.transform = CGAffineTransformScale(CGAffineTransformMakeRotation(angle), 3.0f, 3.0f);
                                              likeImageView.alpha = 0.0f;
                                          }
                                          completion:^(BOOL finished) {
                                              [likeImageView removeFromSuperview];
                                          }];
                     }];
}


- (void)singleTapAction {
    if(self.actionItemClickBlock){
        self.actionItemClickBlock(kAwemeListVedioViewTapTag);
    }
    
//    if([self.hoverTextView isFirstResponder]) {
//        [self.hoverTextView resignFirstResponder];
//    }else {
//        [self showPauseViewAnim:self.playerView.isPlaying];
//        [self.playerView updatePlayerState];
//    }
}

-(void) setIsShowPauseAnimation:(BOOL)isShowPauseAnimation{
    _isShowPauseAnimation = isShowPauseAnimation;
    if(isShowPauseAnimation){
        [self showPauseViewAnim:1.0];
    }else{
        [self showPauseViewAnim:0.0];
    }
}


-(UIView *)vedioGroudView{
    return self.playerView;
}

-(NSString *)vedioUrl{
    return _videoModel.videoPath;
}

#pragma mark - getter

//-(UIImageView *)bgView{
//    if(!_bgView){
//        _bgView = [[UIImageView alloc]init];
//        _bgView.image = IMAGE_NAMED(@"视频图");
//    }
//    return _bgView;
//}

-(UIImageView *)avatar{
    if(!_avatar){
        _avatar = [[UIImageView alloc]init];
        _avatar.image = IMAGE_NAMED(@"头像");
        _avatar.userInteractionEnabled = YES;
        ViewRadius(_avatar, 25);
        _avatar.tag = kAwemeListLikeUserIconTag;
        [_avatar addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]];
//        ViewBorderRadius(_avatar, 25, 1, UICOLOR_WITH_RGBINT_A(0xffffff, 0.1));
    }
    return _avatar;
}

-(RGFocusView *)focus{
    if(!_focus){
        _focus = [[RGFocusView alloc]init];
        AA_WEAK_MAKE(self)weakSelf = self;
        [_focus setFocusBtnClickBlock:^{
            if(weakSelf.actionItemClickBlock){
                weakSelf.actionItemClickBlock(kAwemeListLikeFocusTag);
            }
        }];
    }
    return _focus;
}

-(RGDescriptionView *)descriptionView{
    if(!_descriptionView){
        _descriptionView = [[RGDescriptionView alloc]init];
        
    }
    return _descriptionView;
}

//-(RGVedioNameAnimationView *)animationView{
//    if(!_animationView){
//        _animationView = [[RGVedioNameAnimationView alloc]init];
//        _animationView.text = @"用户创作的原声";
//    }
//    return _animationView;
//}

-(UIImageView *)musicImg{
    if(!_musicImg){
        _musicImg = [[UIImageView alloc]init];
        _musicImg.image = IMAGE_NAMED(@"音乐");
    }
    return _musicImg;
}

-(UIImageView *)share{
    if(!_share){
        _share = [[UIImageView alloc]init];
        _share.image = IMAGE_NAMED(@"转发");
        _share.contentMode = UIViewContentModeCenter;
        _share.userInteractionEnabled = YES;
        _share.tag = kAwemeListLikeShareTag;
        [_share addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]];
    }
    return _share;
}

-(UIImageView *)comment{
    if(!_comment){
        _comment = [[UIImageView alloc]init];
        _comment.contentMode = UIViewContentModeCenter;
        _comment.image = IMAGE_NAMED(@"评论1");
        _comment.userInteractionEnabled = YES;
        _comment.tag = kAwemeListLikeCommentTag;
        [_comment addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]];
    }
    return _comment;
}

-(RGFavoriteView *)favorite{
    if(!_favorite){
        _favorite = [[RGFavoriteView alloc]init];
        AA_WEAK_MAKE(self)weakSelf = self;
        [_favorite setFavoriteBtnClickBlock:^{
            if(weakSelf.actionItemClickBlock){
                weakSelf.actionItemClickBlock(kAwemeListLikeFavoriteTag);
            }
        }];
    }
    return _favorite;
}

-(UILabel *)shareNum{
    if(!_shareNum){
        _shareNum = [[UILabel alloc]init];
        _shareNum.text = @"0";
        _shareNum.textColor = [UIColor whiteColor];
        _shareNum.font = FONT(customFontName, 13);
    }
    return _shareNum;
}

-(UILabel *)commentNum{
    if(!_commentNum){
        _commentNum = [[UILabel alloc]init];
        _commentNum.text = @"0";
        _commentNum.textColor = [UIColor whiteColor];
        _commentNum.font = FONT(customFontName, 13);
    }
    return _commentNum;
}

-(UILabel *)favoriteNum{
    if(!_favoriteNum){
        _favoriteNum = [[UILabel alloc]init];
        _favoriteNum.text = @"0";
        _favoriteNum.textColor = [UIColor whiteColor];
        _favoriteNum.font = FONT(customFontName, 13);
    }
    return _favoriteNum;
}

-(UIView *)container{
    if(!_container){
        _container = [UIView new];
    }
    return _container;
}

-(CAGradientLayer *)gradientLayer{
    if(!_gradientLayer){
        _gradientLayer = [CAGradientLayer layer];
        _gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor, (__bridge id)UICOLOR_WITH_RGBINT_A(0x000000, 0.2).CGColor, (__bridge id)UICOLOR_WITH_RGBINT_A(0x000000, 0.4).CGColor];
        _gradientLayer.locations = @[@0.3, @0.6, @1.0];
        _gradientLayer.startPoint = CGPointMake(0.0f, 0.0f);
        _gradientLayer.endPoint = CGPointMake(0.0f, 1.0f);
    }
    return _gradientLayer;
}

-(UIImageView *)pauseIcon{
    if (!_pauseIcon) {
        _pauseIcon = [[UIImageView alloc] init];
        _pauseIcon.image = [UIImage imageNamed:@"开始"];
        _pauseIcon.contentMode = UIViewContentModeCenter;
        _pauseIcon.layer.zPosition = 3;
//        _pauseIcon.hidden = YES;
    }
    return _pauseIcon;
}

-(UITapGestureRecognizer *)singleTapGesture{
    if(!_singleTapGesture){
        _singleTapGesture =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    }
    return _singleTapGesture;
}

-(UIView *)playerView{
    if(!_playerView){
        _playerView = [[UIView alloc]init];
        _playerView.backgroundColor = [UIColor clearColor];
    }
    return _playerView;
}

-(UIImageView *)vedioBackImg{
    if(!_vedioBackImg){
        _vedioBackImg = [[UIImageView alloc]init];
        _vedioBackImg.contentMode = UIViewContentModeScaleAspectFit;
        _vedioBackImg.backgroundColor = [UIColor blackColor];
    }
    return _vedioBackImg;
}

-(RGBottomCommentToolBar *) bottomCommentToolBar{
    if(!_bottomCommentToolBar){
        _bottomCommentToolBar = [[RGBottomCommentToolBar alloc]init];
    }
    return _bottomCommentToolBar;
}


//-(RGVodPlayerView *)playerView{
//    if(!_playerView){
//        _playerView = [[RGVodPlayerView alloc]init];
//    }
//    return _playerView;
//}

@end
